import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/close_circle.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/doctor_api.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

class ApplyDoctorPage extends StatefulWidget {
  final int doctorID;

  ApplyDoctorPage({Key key, this.doctorID}) : super(key: key);

  @override
  _ApplyDoctorPageState createState() => _ApplyDoctorPageState();
}

class _ApplyDoctorPageState extends State<ApplyDoctorPage> {
  bool _loading = false;
  TextEditingController controller = TextEditingController();
  List<String> _imageList = []; // 从ImagePicker里面选中的图片
  final picker = ImagePicker();
  DateTime lastPopTime; //上次点击时间

// 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    List<Widget> filesListShow = [];
    for (int j = 0; j < _imageList.length; j++) {
      filesListShow
          .add(getFileItemContainer(_imageList[j], j));
    }
    // 增加最后的一个添加图片的图标
    filesListShow.add(GestureDetector(
      onTap: pickImage,
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Colors.lightBlueAccent)),
        child: Icon(Icons.add, color: Colors.lightBlueAccent),
      ),
    ));
    return filesListShow;
  }

// 生成每一张图片的样式
  Widget getItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: FadeInImage.assetNetwork(
                placeholder: 'images/loading.gif', // 占位图
                image: file,
              ),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

// 生成每一张图片的样式（路径来源于文件）
  Widget getFileItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: Image.network(file),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

// 删除图片
  void deleteImage(int index) {
    setState(() {
      _imageList.removeAt(index);
    });
  }

// 在底部显示图片选取方式
  pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
              ),
            ));
  }

// 在底部生成每一项部件
  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

// 拍照或从图库中选取图片
  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);

    if(pickedFile == null) {
      Fluttertoast.showToast(msg: '路径错误', gravity: ToastGravity.TOP);
      return;
    }
    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading(content: '上传中...',);
        });
    upLoadImage(File(pickedFile.path), (imgSrc){
      setState(() {
        _imageList.add(imgSrc);
        Navigator.pop(context);
      });
    });
  }

// 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    if (_loading) {
      return loadingWidget(_loading);
    } else {
      return ListView(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            child: TextField(
              controller: controller,
              keyboardType: TextInputType.multiline,
              decoration: InputDecoration(
                hintText: '请输入发起会话的理由',
                border: InputBorder.none,
              ),
              minLines: 3,
              maxLines: 8,
            ),
          ),
          SizedBox(height: 20),
          Container(
            padding: EdgeInsets.all(8),
            child: GridView.count(
              physics: new NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
              crossAxisCount: 3,
              childAspectRatio: 1.0,
              children: getWidgetList(),
            ),
          )
        ],
      );
    }
  }

// 回到医生列表页面
  _entryDoctorListPage() {
    Navigator.pop(context);
  }

  // 发起会话申请
  _submit() async {
    // TODO: 向后端传送数据
    print(controller.text);
    print(_imageList);
    print(widget.doctorID);

    dynamic res = await sendDiscuss_api({
      'doctorID': widget.doctorID,
      'content': controller.text,
      'files': _imageList
    });

    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            lastPopTime = DateTime.now();
            openAlertDialog(
                context, _entryDoctorListPage, '确认退出编辑，一旦退出，一切将不予保存');
            return new Future.value(false);
          }
          return new Future.value(true);
        },
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('发起会话申请'),
            actions: <Widget>[
              GestureDetector(
                  onTap: _submit,
                  child: Flex(
                    direction: Axis.vertical,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(right: 10),
                        child: Text('发送', style: TextStyle(fontSize: 18)),
                      )
                    ],
                  ))
            ],
          ),
          body: _childLayout(),
        ));
  }
}
